<?php

namespace app\admin\service\auth;

use app\admin\model\Admin;
use think\facade\Db;
use app\admin\service\BaseService;
use support\think\Cache;
class AdminService extends BaseService
{
    /**
     * 获取用户信息
     * @param $jwt
     * @return mixed
     */
    public function Info($jwt)
    {
        $model = new Admin();
        $buttons = $model->getAllPermissions($jwt['id']);
        $admin = $model->where('id', $jwt['id'])->find();
        if (empty($admin)) {
            return fail('用户不存在或已被删除');
        }
        $roleNames = $admin->roles()->column('name');
        $roleCodes = $admin->roles()->column('code');
        $userInfo = [
            'userId' => $admin->id,
            'userName' => $admin->username,
            'image' => getBaseUrl($admin->image),
            'role' => $roleCodes,
            'roles' => implode(',', $roleNames),
            'buttons' => $buttons,
            'baseUrl' => getBaseUrl(),
        ];
        return success($userInfo);
    }
    /**
     * 获取列表
     * @param $data
     * @return mixed
     */
    public function getList($param)
    {
        $model = new Admin();
        $searchFields = ['nickname','username'];//模糊搜索
        $search = ['status'];//精确搜索
        $fields = [];//查询字段
        $list = $this->paginateWithSearch($model, $param, $fields, $searchFields, $search ,'created_at','desc');
        foreach ($list['data'] as &$item) {
            $item['ip_location'] = $this->getIP($item['last_login_ip']);
            $roleNames = $model->find($item['id'])->roles()->column('name');
            $item['role'] = $roleNames;
            $item['role_title'] = implode(',', $roleNames); 
        }
        return success($list);
    }
    /**
     * 添加
     * @param $data
     * @return mixed
     */
    public function Add($data)
    {
      $model = new Admin();
      $Unique = ['username'];
      $empty = ['username','password','role'];
      $check = $this->checkParams($model, $data, $Unique, $empty);
      if ($check !== true) {
          return fail($check['msg']);
      }
      if (isset($data['password'])) {
          $data['password'] = password_hash($data['password'], PASSWORD_BCRYPT,['cost'=>6]);
      }

      $data['created_at'] = time();
      $roles = $data['role'] ?? [];
      unset($data['role']);
      Db::startTrans();
        try{
            $admin_id = $model->insertGetId($data);
            if (!empty($roles)) {
                $adminRoleData = [];
                foreach ($roles as $role_id) {
                    $adminRoleData[] = [
                        'admin_id' => $admin_id,
                        'role_id' => $role_id
                    ];
                }
                Db::name('admin_role')->insertAll($adminRoleData);
            }
            Db::commit();
            // writes('添加', 1);
            return success();
        } catch (\Exception $e) {
            Db::rollback();
            return fail('操作失败:' . $e->getMessage());
        }
    }
    /**
     * 编辑
     * @param $id
     * @param $data
     * @return mixed
     */
    public function Edit($id, $data)
    {
      $model = new Admin();
      $res = $model->where('id', $id)->find();
      if (empty($res)) {
        return fail('用户不存在');
      }
      $Unique = ['username'];
      $empty = ['username'];
      $data['id'] = $id;
      $check = $this->checkParams($model, $data, $Unique, $empty);
      if ($check !== true) {
          return fail($check['msg']);
      }
      if (isset($data['password']) && !empty($data['password'])) {
          $data['password'] = password_hash($data['password'], PASSWORD_BCRYPT,['cost'=>6]);
      } else {
          unset($data['password']);
      }
      $roles = $data['role'] ?? [];
      unset($data['role']);
      Db::startTrans();
      unset($data['id']);
        try{
            $data['updated_at'] = time();
            Db::name('admins')->where('id', $id)->update($data);
            Db::name('admin_role')->where('admin_id', $id)->delete();
            if (!empty($roles)) {
                $adminRoleData = [];
                foreach ($roles as $role_id) {
                    $adminRoleData[] = [
                        'admin_id' => $id,
                        'role_id' => $role_id
                    ];
                }
                Db::name('admin_role')->insertAll($adminRoleData);
            }
            Db::commit();
            $permissions = $model->getAllPermissions($id);
            Cache::set('user_permission_' . $id, $permissions, 0);
            // writes('编辑', 2);
            return success();
        } catch (\Exception $e) {
            Db::rollback();
            return fail('操作失败:' . $e->getMessage());
        }
    }
    /**
     * 删除
     * @param $ids
     * @return mixed
     */
    public function Delete($ids)
    {
      $model = new Admin();
      $ids = array_filter(array_unique($ids));
      if (empty($ids)) {
          return fail('请选择要删除的数据');
      }
      foreach ($ids as $id) {
          if (!is_numeric($id) || $id <= 0) {
              return fail('包含错误ID值'.$id);
          }
      }
      if (in_array(1, $ids)) {
          return fail('不可删除ID：1');
      }
      $ids = array_map('intval', $ids);
      Db::startTrans();
        try{
            $model->whereIn('id', $ids)->delete();
            Db::name('admin_role')->whereIn('admin_id', $ids)->delete();
            Db::commit();
            foreach ($ids as $id) {
                Cache::delete('user_permission_' . $id);
            }
            // writes('删除', 3);
            return success();
        } catch (\Exception $e) {
            Db::rollback();
            return fail('操作失败:' . $e->getMessage());
        }
    }
}
